package org.yimon.tool.algo.leetcode;

import java.util.Stack;

/**
 * @Author yimon.gao
 * @Description 删除链表倒数第N个节点
 * @Date 2024/8/22 下午3:53
 */
public class LeetCode_019_RemoveNthFromEnd {

    public static void main(String[] args) {
        System.out.println(LeetCode_019_RemoveNthFromEnd.removeNthFromEnd(new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5))))), 2));
    }

    public static ListNode removeNthFromEnd(ListNode head, int n) {
        //特殊情况判断
        if (head == null || n <= 0) {
            return head;
        }
       //定义栈，将每个节点元素压入栈中
        Stack<ListNode> stack = new Stack<>();
        ListNode pushNode = head;
        while (pushNode != null) {
            stack.push(pushNode);
            pushNode = pushNode.next;
        }
        //开始进行弹出
        ListNode pre = null;//这个pre就是需要删除的元素节点
        for (int i = 0; i < n; i++) {
            if(stack.isEmpty()) {
                pre = null;
            } else {
                pre = stack.peek();
                stack.pop();
            }
        }
        if(pre == null) { //删除的元素为null，说明n的长度超出了链表的长度
            return head;
        }
        if(stack.isEmpty()) {//删除的元素不为null，且栈为空；则说明删除的元素正好是头节点
            return pre.next;
        }
        ListNode pop = stack.pop();//其他情况则说明删除的元素是链表的中间节点
        pop.next = pre.next;//删除pre

        return head;
    }

    private static class ListNode {
        int val;
        ListNode next;

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }

        @Override
        public String toString() {
            return "ListNode{" +
                    "val=" + val +
                    ", next=" + next +
                    '}';
        }
    }
}
